
import React from "react";
import Controller from "@/Controller"
import Icon from '@ant-design/icons';
import classnames from 'classnames';
import { ITask } from "@/Controller/State/task";
import styles from './index.module.less';
import { Dropdown, MenuProps } from "antd";


/** 任务容器 */
export function TaskContainer() {

    const tasklist = Controller.instance.useMemo(s => s.taskInfo.list, []);

    const taskGroup = React.useMemo(() => {
        const g = new Map<string, ITask[]>()
        tasklist.forEach(t => {
            if (g.has(t.moduleKey)) {
                g.get(t.moduleKey)?.push(t)
            } else {
                g.set(t.moduleKey, [t]);
            }
        })
        return Array.from(g.values());
    }, [tasklist])

    return (
        taskGroup.map(tasks => {
            return (
                <TaskGroup tasks={tasks} />
            )
        })
    )
}

/** 任务组 */
function TaskGroup(props: { tasks: ITask[] }) {

    const taskList = Controller.instance.useMemo(s => s.taskInfo.list, [])

    const { tasks } = props;

    const focus = React.useMemo(() => tasks.some(e => e.zIndex === taskList.length - 1), [taskList.length, tasks])

    const className = React.useMemo(() => classnames(styles.taskGroup, { [styles.plural]: tasks.length > 1, [styles.focus]: focus }), [focus, tasks.length])

    const toTask = React.useCallback((task: ITask) => {

        const tl = [...taskList];
        const tf = (tl.sort((a, b) => b.zIndex - a.zIndex), tl[0]);

        if (tf === task) {
            Controller.instance.run(async s => {
                task.minimize = !task.minimize;
                s.taskInfo.list = [...s.taskInfo.list]
            })
        } else {
            Controller.instance.askToTop({ id: task.id })
        }
    }, [taskList])

    const dropdownItems = React.useMemo<MenuProps['items']>(() => {
        return tasks.map((e, i) => {
            return {
                key: i,
                label: e.name,
                icon: <Icon component={e.icon} />,
                onClick: () => { toTask(e); }
            }
        })
    }, [tasks, toTask])

    const onClick = React.useCallback(() => {
        if (tasks.length === 1) {
            toTask(tasks[0]);
        } else {
            console.log(tasks);
        }
    }, [tasks, toTask])

    return (
        <Dropdown disabled={tasks.length <= 1} menu={{ items: dropdownItems }} >
            <div className={className} onClick={onClick}>
                <i /><i />
                <Icon component={tasks[0].icon} style={{ fontSize: 20 }} />
                <span>{tasks[0].name}</span>
            </div>
        </Dropdown>
    )
}
